package diona.model

import net.liftweb.squerylrecord.KeyedRecord
import org.squeryl.annotations.Column
import net.liftweb.record.field.{StringField, LongField}
import net.liftweb.squerylrecord.RecordTypeMode._
import java.awt.image.BufferedImage
import java.io.File
import java.util.UUID
import javax.imageio.ImageIO
import net.liftweb.util.Props
import net.liftweb.record.{MetaRecord, Record}

class ImageInfo extends Record[ImageInfo] with KeyedRecord[Long]
{
  override def meta = ImageInfo

  @Column(name = "id")
  override val idField = new LongField(this)

  val dir = new StringField(this, "")
  val file = new StringField(this, "")
  val sharingGroup = new StringField(this, "")
  val userId = new LongField(this)

  //lazy val user = PublisherSchema.userToImages.right(this)
}

object ImageInfo extends ImageInfo with MetaRecord[ImageInfo]
{
  @volatile var defaultDir: () => String = () => Props.get("images.defaultDir").open_!

  @volatile def byId: (Long) => Option[ImageInfo] =
    (id) => inTransaction {PublisherSchema.images.lookup(id)}

  @volatile def byUser: (User) => List[ImageInfo] =
    (user) => inTransaction {PublisherSchema.images.where(_.userId === user.id).toList}


  def save(image: BufferedImage, user: User, groupId: String)
  {
    val imageFile = new File(defaultDir(), UUID.randomUUID + ".jpg")
    val fileName = imageFile.getName
    ImageIO.write(image, "jpg", imageFile)
    val imageInfo = ImageInfo.createRecord.dir(defaultDir()).file(fileName).sharingGroup(groupId).userId(user.id.value)
    inTransaction {PublisherSchema.images.insert(imageInfo)}
  }
}
